package net.hn.hnms.biz.safety.trinity.company.service;

import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.safety.trinity.model.RiskControlVo;
import net.hn.hnms.biz.safety.trinity.dao.RiskControlListDao;
import net.hn.hnms.biz.safety.trinity.dao.RiskControlMeasureRecordDao;
import net.hn.hnms.biz.safety.trinity.entity.*;
import net.hn.hnms.biz.safety.trinity.service.RiskControlService;
import net.hn.hnms.biz.safety.trinity.until.MineName;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 智呈物联 nzw
 * @date 2023/1/5
 */

@Service
@RequiredArgsConstructor
public class RiskControlCompanyService {
    private final JdbcTemplate locationJdbcTemplate;

    RiskControlListDao riskControlListDao;

    RiskControlMeasureRecordDao riskControlMeasureRecordDao;

    RiskControlService riskControlService;

    private MineName mineName;

    @Autowired
    public void setRiskControlListDao(RiskControlListDao riskControlListDao) {
        this.riskControlListDao = riskControlListDao;
    }

    @Autowired
    public void setRiskControlMeasureRecordDao(RiskControlMeasureRecordDao riskControlMeasureRecordDao) {
        this.riskControlMeasureRecordDao = riskControlMeasureRecordDao;
    }

    @Autowired
    public void setMineName(MineName mineName) {
        this.mineName = mineName;
    }

    @Autowired
    public void setRiskControlService(RiskControlService riskControlService) {
        this.riskControlService = riskControlService;
    }

    /**
     * 风险等级处理
     * @param list 风险列表
     * @return 处理后的风险对象
     */
    private RiskLevelCountVO dealWithRiskLevel(List<Map<String,Object>> list){
        RiskLevelCountVO riskLevelCountVO = new RiskLevelCountVO();

        for (Map<String,Object> map :list){
            String level = map.get("risk_level")+"";
            String count = "";
            if (map.get("count")!=null&&!"".equals(map.get("count"))){
                count = map.get("count")+"";
            }else {
                count = "0";
            }
            switch (level){
                case "4":
                    riskLevelCountVO.setMajor(Integer.parseInt(count));
                    break;
                case "3":
                    riskLevelCountVO.setNormalA(Integer.parseInt(count));
                    break;
                case "2":
                    riskLevelCountVO.setNormalB(Integer.parseInt(count));
                    break;
                case "1":
                    riskLevelCountVO.setNormalC(Integer.parseInt(count));
                    break;
            }
        }
        return riskLevelCountVO;
    }

    public RiskControlVo riskControl(String companyCode){
        RiskControlVo riskControlVo = new RiskControlVo();
        //风险总数
        riskControlVo.setRiskCount(riskControlListDao.countAllByMineCodeOrCompanyCode("",companyCode));
        //重大风险
        riskControlVo.setMajorRisk(riskControlListDao.countAllByRiskLevel("4",companyCode));
        //风险管控记录
        riskControlVo.setControlRecords(riskControlMeasureRecordDao.countAll(companyCode));
        return riskControlVo;
    }

    public ResponsePage<RiskCompanyVO> page(PageQuery pageQuery, String mineCode, String level){
        String sql = "SELECT\n" +
                "\trcl.*,\n" +
//                "\trcm.control_measure,\n" +
//                "\trcm.duty_dept_codes,\n" +
//                "\trcm.duty_dept_names,\n" +
                "\trl.risk_location_name\n" +
                "\tFROM\n" +
                "\trisk_control_list rcl\n" +
//                "\tLEFT JOIN risk_control_measure rcm ON rcl.risk_id = rcm.risk_id \n" +
                "\tLEFT JOIN risk_location rl ON rcl.risk_location_id = rl.risk_location_id";
        String count = "SELECT\n" +
                "\tcount(1)\n" +
                "\tFROM\n" +
                "\trisk_control_list rcl \n" +
//                "\tLEFT JOIN risk_control_measure rcm ON rcl.risk_id = rcm.risk_id \n" +
                "\tLEFT JOIN risk_location rl ON rcl.risk_location_id = rl.risk_location_id";
        String where = " WHERE\n" +
                "\t1 = 1";
        if (mineCode!=null&&!"".equals(mineCode)){
            where += " AND rcl.mine_code = '"+mineCode+"'";
        }
        if (level!=null&&!"".equals(level)){
            switch(level){
                case "A":
                    level = "较大风险（二级）";
                    break;
                case "B":
                    level = "一般风险（三级）";
                    break;
                case "C":
                    level = "低风险（四级）";
                    break;
                default:
                    level = "重大风险（一级）";
                    break;
            }
            where += " AND rcl.risk_level = '"+level+"'";
        }

        //分页条件
        Integer pageSize = pageQuery.getPageSize();
        if (pageSize==null){
            pageSize = 10;
        }
        Integer pageNum = pageQuery.getPageNum();
        if (pageNum==null||pageNum==0){
            pageNum=1;
        }
        String page = " order by rcl.data_time desc LIMIT "+pageSize+" OFFSET "+(pageNum-1)*pageSize;

        List<Map<String,Object>> riskList = locationJdbcTemplate.queryForList(sql+where+page);
        List<RiskCompanyVO> riskCompanyVOList = new ArrayList<>();
        for (Map<String,Object> map:riskList){
            RiskCompanyVO riskCompanyVO = new RiskCompanyVO();

            String riskId = map.get("risk_id")+"";

            String controlMeasureSql = "SELECT\n" +
                    "\tcontrol_measure,\n" +
                    "\tduty_dept_codes,\n" +
                    "\tduty_dept_names \n" +
                    "FROM\n" +
                    "\trisk_control_measure \n" +
                    "WHERE\n" +
                    "\trisk_id = '"+riskId+"'";
            List<Map<String,Object>> controlMeasureList = locationJdbcTemplate.queryForList(controlMeasureSql);

            StringBuffer controlMeasure = new StringBuffer("");
            String deptCode = "";
            String deptName = "";
            if (controlMeasureList!=null&&controlMeasureList.size()!=0){
                controlMeasureList.forEach(c -> {
                    controlMeasure.append(c.get("control_measure") + "");
                });
                deptCode = controlMeasureList.get(0).get("duty_dept_codes") + "";
                deptName = controlMeasureList.get(0).get("duty_dept_names") + "";
            }

            riskCompanyVO.setMineName(mineName.getMineName(map.get("mine_code")+""));
            riskCompanyVO.setMineCode(map.get("mine_code")+"");
            riskCompanyVO.setCompanyName(mineName.getParentMineName(map.get("mine_code")+""));
            riskCompanyVO.setControlMeasure(controlMeasure+"");
            riskCompanyVO.setResponsibility(deptName);
            riskCompanyVO.setRiskLevel(getRiskLevelName(map.get("risk_level")+""));
            riskCompanyVO.setRiskPlace(map.get("risk_location_name")+"");
            riskCompanyVO.setRiskType(riskControlService.getRiskTypeName(map.get("risk_class")+""));
//            riskCompanyVO.setSupervise(map);

            riskCompanyVOList.add(riskCompanyVO);
        }
        Map<String,Object> map = locationJdbcTemplate.queryForMap(count+where);
        return new ResponsePage<RiskCompanyVO>(riskCompanyVOList,Integer.parseInt(map.get("count")+""));
    }

    public String getRiskLevelName(String riskLevel){
        if ("4".equals(riskLevel)){
            return "重大风险";
        }else if ("3".equals(riskLevel)){
            return "高风险";
        } else if ("2".equals(riskLevel)){
            return "一般风险";
        }else if ("1".equals(riskLevel)){
            return "低风险";
        }
        return "";
    }

    public RiskLevelCountVO riskLevel(){
        List<Map<String,Object>> list = riskControlListDao.riskLevel();
        return dealWithRiskLevel(list);
    }

    public List<RiskCompanyLevelVO> riskLevelByMineCode(){
        List<String> mineCodes = riskControlListDao.riskMineCode();
        List<RiskCompanyLevelVO> riskCompanyLevelVOArrayList = new ArrayList<>();
        for (String mineCode:mineCodes){
            RiskCompanyLevelVO riskCompanyLevelVO = new RiskCompanyLevelVO();
            List<Map<String,Object>> list = riskControlListDao.riskLevelByMineCode(mineCode);

            riskCompanyLevelVO.setMineCode(mineCode);
            riskCompanyLevelVO.setMineName(mineName.getMineName(mineCode));
            riskCompanyLevelVO.setRiskLevelCountVO(dealWithRiskLevel(list));
            riskCompanyLevelVOArrayList.add(riskCompanyLevelVO);
        }

        return riskCompanyLevelVOArrayList;
    }

    public void getRiskLevelYear(RiskHiddenDangerLevelVO riskHiddenDangerLevelVO){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        List<Map<String,Object>> list = riskControlListDao.getRiskLevelYear(simpleDateFormat.format(new Date())+"-01-01");
        list.forEach(map -> {
            String riskLevel = map.get("risk_level")+"";
            String count = map.get("count")+"";
            switch(riskLevel){
                case "2":
                    riskHiddenDangerLevelVO.setNormalB(count);
                    break;
                case "3":
                    riskHiddenDangerLevelVO.setNormalA(count);
                    break;
                case "4":
                    riskHiddenDangerLevelVO.setMajor(count);
                    break;
                default:
                    riskHiddenDangerLevelVO.setNormalC(count);
                    break;
            }
        });
    }

    public RiskTypeVO riskType(){
        List<Map<String,Object>> list = riskControlListDao.getRiskType();
        String[] typeName = {"火灾", "水灾", "瓦斯爆炸","煤尘爆炸", "顶板", "运输系统"};
        List<String> typeNameList = Arrays.asList(typeName);
        String[] typeNum = {"0", "0", "0","0", "0", "0"};
        List<String> typeNumList = new LinkedList<>(Arrays.asList(typeNum));
        list.forEach(map -> {
            String riskType = map.get("risk_class")+"";
            switch (riskType){
                case "1":
                    typeNumList.set(0,map.get("count")+"");
                    break;
                case "2":
                    typeNumList.set(1,map.get("count")+"");
                    break;
                case "3":
                    typeNumList.set(2,map.get("count")+"");
                    break;
                case "4":
                    typeNumList.set(3,map.get("count")+"");
                    break;
                case "5":
                    typeNumList.set(4,map.get("count")+"");
                    break;
                case "6":
                    typeNumList.set(5,map.get("count")+"");
                    break;
            }
        });
        RiskTypeVO riskTypeVO = new RiskTypeVO();
        riskTypeVO.setNum(typeNumList);
        riskTypeVO.setType(typeNameList);

        return riskTypeVO;
    }

}
